package com.by.service;

import com.by.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    //模拟数据库
    Map<String, UserInfo> userInfoMap = new HashMap<String, UserInfo>();

    public void initUserInfoMap() {
        userInfoMap.put("admin", new UserInfo("jl", passwordEncoder.encode("211314")));
        userInfoMap.put("gp", new UserInfo("gp", passwordEncoder.encode("211314")));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initUserInfoMap();

        //1.从数据库查询用户
        UserInfo userInfo = userInfoMap.get(username);
        if (userInfo == null) {
            return null;
        }

        //2.提供UserDetails（密码）,注意对比密码是security框架的事。程序员只需提供数据。
        // {noop} 明文对比
        String password = userInfo.getPassword();

//        List<GrantedAuthority> list = new ArrayList<>();
//        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
//        list.add(new SimpleGrantedAuthority("add"));
//        list.add(new SimpleGrantedAuthority("delete"));
//        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));


        List<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        if ("jl".equals(username)) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("aaa"));
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("bbb"));
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMINISTRATORS"));
        } else {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("bbb"));
            //授权时，必须去掉ROLE_
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMINISTRATORS"));
        }


        User user = new User(username, password, simpleGrantedAuthorities);


        return user;
    }
}
